//
//  MagazineController.m
//  Jingjing
//
//  Created by Maxwell Rose on 15/11/9.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "MagazineController.h"
#import "SearchViewController.h"
#import "MagazineCollectionController.h"
#import "MagazineModel.h"
#import "SearchViewController.h"

static NSString *const MagazineCellIdentifier = @"MagazineCellIdentifier";

@interface MagazineController ()<UITextFieldDelegate>
@property (weak, nonatomic) UITextField *searchField;
@property (strong, nonatomic) MagazineCollectionController *magazineVC;
@property (strong, nonatomic) WMPageController *pageVC;

@property (strong, nonatomic) NSMutableArray *dataSources;

@property (strong, nonatomic) UITableView *blankTable;

@property (strong, nonatomic) UIView *noDataView;

@property (strong, nonatomic) UIView *noNet;

@end

@implementation MagazineController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"杂志";
    self.dataSources = [NSMutableArray array];
//    [_tableView.header beginRefreshing];
    [self addSearchView];
    [self addBlankTable];
    [self refresh];
}

- (void)viewWillAppear:(BOOL)animated{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)addSearchView{
    UIView *searchBackgroudView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0, SCREEN_WIDTH, 44)];
    searchBackgroudView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    searchBackgroudView.layer.borderWidth = 0.5;
    searchBackgroudView.layer.borderColor = [[UIColor colorWithWhite:0.702 alpha:1.000] CGColor];
    [self.view addSubview:searchBackgroudView];
    
    //    添加搜索框
    UITextField *searchField = [[UITextField alloc]initWithFrame:CGRectMake(16, 6, SCREEN_WIDTH -  16 - 16, 32)];
    searchField.placeholder = @"请输入您要搜索的杂志";
    searchField.delegate = self;
    searchField.borderStyle = UITextBorderStyleNone;
    searchField.font = [UIFont systemFontOfSize:14];
    searchField.backgroundColor = [UIColor whiteColor];
    searchField.textColor = [UIColor colorWithWhite:0.000 alpha:0.300];
    searchField.layer.cornerRadius = 4;
    
    
    UIImageView *leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_search"]];
    CGRect rect = leftView.frame;
    rect.origin.x += 5;
    leftView.frame = rect;
    UIView *leftBackgroudView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, leftView.frame.size.width + 5, leftView.frame.size.height)];
    [leftBackgroudView addSubview:leftView];
    
    searchField.leftView = leftBackgroudView;
    searchField.leftViewMode = UITextFieldViewModeAlways;
    self.searchField = searchField;
    [searchBackgroudView addSubview:searchField];

}

- (void)addBlankTable{
    _blankTable = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _blankTable.frame = CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height - 44 - 49);
    _blankTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _blankTable.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refresh];
    }];
    [self.view addSubview:_blankTable];
    self.noDataView.hidden = FALSE;
    
    
}

- (void)addWMPageControllerWithData:(NSArray *)dataSources{
    NSMutableArray *keys = [NSMutableArray array];
    NSMutableArray *controllerClasses = [NSMutableArray array];
    NSMutableArray *titles = [NSMutableArray array];
    
    for (MagazineModel *model in  dataSources) {
        [keys addObject:@"model"];
        [controllerClasses addObject:[MagazineCollectionController class]];
        [titles addObject:model.typeTitle];
    }
    [_pageVC.view removeFromSuperview];
    self.pageVC = [[WMPageController alloc]initWithViewControllerClasses:controllerClasses andTheirTitles:titles];
    _pageVC.keys = keys;
    _pageVC.values = dataSources;
    _pageVC.view.frame = CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height - 44);
    _pageVC.pageAnimatable = YES;
//    _pageVC.menuItemWidth = 120;
    _pageVC.itemsWidths = [self itemWidthsWithModels:_dataSources];
    _pageVC.postNotification = YES;
    _pageVC.bounces = YES;
    _pageVC.menuViewStyle = WMMenuViewStyleLine;
    _pageVC.menuBGColor = [UIColor colorWithWhite:0.902 alpha:1.000];
    _pageVC.titleColorSelected = [UIColor blackColor];

    [self.view addSubview:_pageVC.view];
}

- (NSArray *)itemWidthsWithModels:(NSArray *)theArray{
    NSMutableArray *widths = [NSMutableArray array];
    for (MagazineModel *model in theArray) {
        NSNumber *width = [NSNumber numberWithFloat:[self calcWidthWithSting:model.typeTitle]];
        [widths addObject:width];
    }
    return [widths copy];
}

- (CGFloat)calcWidthWithSting:(NSString *)aString{
    CGFloat width = [UILabel width:aString heightOfFatherView:20 textFont:[UIFont systemFontOfSize:18]];
    if (width >= 200) {
        width = 200;
    }
    return width;
}

- (void)refresh{
    static NSInteger nextPage = 1;
    if (_dataSources.count == 0) {
        nextPage = 0;
    }
    //发送网络请求获取视频列表
    NSDictionary *parameter = @{
                                @"page.pn":[NSNumber numberWithInteger: nextPage == 0 ? 1 : nextPage]
                                };
    //发送网络请求获取视频列表
    [AppGlobalClass PostDataWithNSstring:kLinkOfMagazineClassList withDictionary:parameter success:^(NSDictionary *dictionary) {
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,dictionary);
        if ([[dictionary objectForKey:@"success"] isEqualToNumber:@YES])
        {
            NSDictionary *responseDate = [dictionary[@"responseData"] firstObject];
            NSInteger pages = [responseDate[@"pages"] integerValue];
            NSInteger currentPage = [responseDate[@"page"] integerValue];
            if (pages == 1) {//如果只有一页数据则情况数据，重新加载
                [self.dataSources removeAllObjects];
            }
            NSArray * rowsArray = responseDate[@"rows"];
            for (NSDictionary * dataDict in rowsArray)
            {
                MagazineModel * model = [[MagazineModel alloc]init];
                [model setValuesForKeysWithDictionary:dataDict];
                model.navigationController = self.navigationController;
                
                [_dataSources addObject:model];
            }
        
            if (_dataSources.count > 0)
            {
                [self addWMPageControllerWithData:_dataSources];
                
            }
            else{
                self.noDataView.hidden = FALSE;
            }
            
            if (pages > 1) {
                nextPage = currentPage + 1;
                if (pages > currentPage) {
                    [self refresh];
                }
                
            }
           
            
        }else{
            //没有真确返回
            [self.dataSources removeAllObjects];
            self.noDataView.hidden = FALSE;
            
        }
        [_blankTable.header endRefreshing];
        
    } failure:^(NSError *error) {
        NSLog(@"----%@",error);
        self.noDataView.hidden = FALSE;
        self.noNet.hidden = YES;

        [_dataSources removeAllObjects];
        [_blankTable.header endRefreshing];
        
    } networkerror:^(NSString *networkerror) {
        NSLog(@"----");
        self.noNet.hidden = FALSE;
        self.noDataView.hidden = YES;

        [_dataSources removeAllObjects];
        
        [_blankTable.header endRefreshing];
        
    }];

}

- (void)historyButtonAction:(UIButton *)btn{
    NSLog(@" %d | %s ",__LINE__,__FUNCTION__);
    _magazineVC = [[MagazineCollectionController alloc]init];
    [self.navigationController pushViewController:_magazineVC animated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - <UITextFiled View Delegate>
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self.searchField resignFirstResponder];
    SearchViewController *vc = [[SearchViewController alloc]init];                                             
    [self.navigationController pushViewController:vc animated:YES];
}


//没网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 235)];
        _noNet.center = CGPointMake(self.view.center.x, self.view.center.y - 44);
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];
        [self.view addSubview:_noNet];
    }
    [self.view bringSubviewToFront:_noNet];
    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        _noDataView.center =CGPointMake(self.view.center.x, self.view.center.y - 44);
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 200, 200);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 40, 200, 44)];
        label.text = @"暂无数据";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
        [self.view addSubview:_noDataView];
    }
    [self.view bringSubviewToFront:_noDataView];
    return _noDataView;
}

- (void)noResultButtonAction:(id)sender
{
    [_blankTable.header beginRefreshing];
}
@end
